import {  getKnowledgeList, getKnowledgeDetail, getKnowLedgeKid } from '@/services';
import { IknowledgeDetail, IknowledgeItem , IknowledgeDetailChild} from '@/types';
import { Effect, Reducer } from 'umi';
export interface KnowledgeModelState {
  knowledgeList: IknowledgeItem[];
  knowledgeDetail: Partial<IknowledgeDetail>; // 把接口的属性变成可选的
  knowledgsId:Partial<IknowledgeDetailChild>
}

export interface KnowledgeModelType {
  namespace: 'knowledge';
  state: KnowledgeModelState;

  effects: {
    getKnowledgeList: Effect;
    getKnowledgeDetail: Effect;
    getKnowLedgeKid: Effect;
  };
  reducers: {
    save: Reducer<KnowledgeModelState>;
  };
}

const KnowledgeModel: KnowledgeModelType = {
  // 数据模型，用来隔离数据防止相互影响
  namespace: 'knowledge',

  // 数据模型状态，相当于vuex的state
  state: {
    knowledgeList: [],
    knowledgeDetail: {},
    knowledgsId:{}
  },

  // 异步操作，相当于vuex的action
  effects: {
    // 先简单记忆，*相当于async，yield相当于await
    *getKnowledgeList({ payload }, { call, put }) {
      let result = yield call(getKnowledgeList, payload);
      localStorage.setItem("DetailId",JSON.stringify(result.data))
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            knowledgeList: result.data[0],
          },
        });
      }
    },
    *getKnowledgeDetail({ payload }, { call, put }) {
      
      let result = yield call(getKnowledgeDetail, payload);
      localStorage.setItem("kid",JSON.stringify(result.data))
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            knowledgeDetail: result.data,
          },
        });
      }
    },
    *getKnowLedgeKid({ payload }, { call, put }) {
      let result = yield call(getKnowLedgeKid, payload);
      localStorage.setItem("toc",result.data.toc)
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            knowledgsId: result.data,
          },
        });
      }
    },
  },

  // 同步操作，相当于vuex的mutation
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};

export default KnowledgeModel;
